<template>
  <div class="order-page font-inter bg-gray-50 text-gray-800">
    <!-- 头部导航栏 -->

    <main class="py-6 md:py-10">
      <div class="container mx-auto px-4">
        <!-- 路径导航 -->
        <div class="mb-6 text-sm text-gray-500">
          <router-link to="/" class="hover:text-primary">首页</router-link>
          <span class="fa fa-angle-right mx-2 text-xs"></span>
          <router-link to="/cart" class="hover:text-primary">购物车</router-link>
          <span class="fa fa-angle-right mx-2 text-xs"></span>
          <span>提交订单</span>
        </div>

        <h2 class="text-2xl font-bold text-gray-800 mb-6">提交订单</h2>

        <!-- 订单步骤指示器 -->
        <div class="bg-white rounded-xl shadow-sm p-4 mb-6">
          <div class="flex items-center justify-between">
            <div class="flex flex-col items-center w-1/3">
              <div class="w-10 h-10 rounded-full bg-primary text-white flex items-center justify-center font-bold mb-2">1</div>
              <p class="text-sm font-medium text-primary">确认订单</p>
            </div>
            <div class="h-1 flex-1 bg-primary"></div>
            <div class="flex flex-col items-center w-1/3">
              <div class="w-10 h-10 rounded-full bg-gray-200 text-gray-500 flex items-center justify-center font-bold mb-2">2</div>
              <p class="text-sm font-medium text-gray-500">支付</p>
            </div>
            <div class="h-1 flex-1 bg-gray-200"></div>
            <div class="flex flex-col items-center w-1/3">
              <div class="w-10 h-10 rounded-full bg-gray-200 text-gray-500 flex items-center justify-center font-bold mb-2">3</div>
              <p class="text-sm font-medium text-gray-500">完成</p>
            </div>
          </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <!-- 订单信息 -->
          <div class="lg:col-span-2 space-y-6">
            <!-- 收货地址 -->
            <div class="bg-white rounded-xl shadow-sm overflow-hidden">
              <div class="p-6 border-b border-gray-100 flex justify-between items-center">
                <h3 class="font-bold text-lg text-gray-800">收货地址</h3>

              </div>

              <div class="p-6">
                <!-- 动态渲染所有地址 - 替换原固定2个地址的写法 -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4" v-if="addresses.length > 0">
                  <div
                    v-for="(address, index) in addresses"
                    :key="address.id || index"
                    :class="selectedAddressIndex === index ? 'border-2 border-primary' : 'border border-gray-200 hover:border-primary/50'"
                    class="rounded-lg p-4 relative cursor-pointer transition-colors"
                    @click="selectAddress(index)"
                  >
                    <!-- 选中状态图标 -->
                    <div
                      v-if="selectedAddressIndex === index"
                      class="absolute top-3 right-3 w-5 h-5 rounded-full bg-primary flex items-center justify-center"
                    >
                      <span class="fa fa-check text-white text-xs"></span>
                    </div>
                    <!-- 地址信息展示 -->
                    <p class="font-medium">{{ address.recipient_name }}</p>
                    <p class="text-gray-600 mt-1">{{ formatPhone(address.phone) }}</p>
                    <p class="text-gray-600 mt-1">{{ address.province }} {{ address.city }}{{ address.county }}  {{ address.detail_address }}</p>
                    <!-- 默认地址标签 -->
                    <span v-if="address.is_default" class="inline-block mt-2 px-2 py-1 bg-primary/10 text-primary text-xs rounded">默认地址</span>
                  </div>
                </div>

                <!-- 无地址时的提示 -->
                <div v-else class="text-center py-8 text-gray-500">
                  <p class="mb-4">暂无收货地址，请添加新地址</p>
                </div>

                <button @click="quaddaddress()"  class="mt-4 w-full border-2 border-dashed border-gray-300 text-gray-500 hover:border-primary hover:text-primary py-3 rounded-lg transition-colors text-sm font-medium flex items-center justify-center">
                  <span class="fa fa-plus mr-2"></span>
                  添加新地址
                </button>

              </div>
            </div>


           <!-- 配送方式 -->
          <div class="bg-white rounded-xl shadow-sm overflow-hidden">
            <div class="p-6 border-b border-gray-100">
              <h3 class="font-bold text-lg text-gray-800">配送方式</h3>
            </div>
            <div class="p-6">
              <div class="space-y-4">
                <!-- 普通快递 -->
                <div
                  class="flex items-center p-4 rounded-lg relative cursor-pointer transition-colors"
                  :class="selectedDeliveryIndex === 0 ? 'border-2 border-primary' : 'border border-gray-200 hover:border-primary/50'"
                  @click="selectDelivery(0)"
                >
                  <!-- 选中图标：仅选中时显示 -->
                  <div
                    v-if="selectedDeliveryIndex === 0"
                    class="absolute top-4 right-4 w-5 h-5 rounded-full bg-primary flex items-center justify-center"
                  >
                    <span class="fa fa-check text-white text-xs"></span>
                  </div>
                  <div :class="selectedDeliveryIndex === 0 ? 'mr-4 text-primary' : 'mr-4 text-gray-400'">
                    <span class="fa fa-truck text-xl"></span>
                  </div>
                  <div>
                    <p class="font-medium">{{ deliveryOptions[0].name }}</p>
                    <p class="text-gray-500 text-sm">{{ deliveryOptions[0].desc }}</p>
                  </div>
                  <div class="ml-auto font-medium">¥{{ deliveryOptions[0].price.toFixed(2) }}</div>
                </div>
                <!-- 加急快递 -->
                <div
                  class="flex items-center p-4 rounded-lg relative cursor-pointer transition-colors"
                  :class="selectedDeliveryIndex === 1 ? 'border-2 border-primary' : 'border border-gray-200 hover:border-primary/50'"
                  @click="selectDelivery(1)"
                >
                  <!-- 选中图标：仅选中时显示 -->
                  <div
                    v-if="selectedDeliveryIndex === 1"
                    class="absolute top-4 right-4 w-5 h-5 rounded-full bg-primary flex items-center justify-center"
                  >
                    <span class="fa fa-check text-white text-xs"></span>
                  </div>
                  <div :class="selectedDeliveryIndex === 1 ? 'mr-4 text-primary' : 'mr-4 text-gray-400'">
                    <span class="fa fa-rocket text-xl"></span>
                  </div>
                  <div>
                    <p class="font-medium">{{ deliveryOptions[1].name }}</p>
                    <p class="text-gray-500 text-sm">{{ deliveryOptions[1].desc }}</p>
                  </div>
                  <div class="ml-auto font-medium">¥{{ deliveryOptions[1].price.toFixed(2) }}</div>
                </div>
              </div>
            </div>
          </div>


          <!-- 支付方式 -->
          <div class="bg-white rounded-xl shadow-sm overflow-hidden">
            <div class="p-6 border-b border-gray-100">
              <h3 class="font-bold text-lg text-gray-800">支付方式</h3>
            </div>
            <div class="p-6">
              <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <!-- 在线支付 -->
                <div
                  class="flex items-center p-4 rounded-lg cursor-pointer transition-colors"
                  :class="selectedPaymentIndex === 0 ? 'border-2 border-primary' : 'border border-gray-200 hover:border-primary/50'"
                  @click="selectPayment(0)"
                >
                  <div :class="selectedPaymentIndex === 0 ? 'mr-4 text-primary' : 'mr-4 text-gray-400'">
                    <span class="fa fa-credit-card text-xl"></span>
                  </div>
                  <div>
                    <p class="font-medium">{{ paymentOptions[0].name }}</p>
                    <p class="text-gray-500 text-xs">{{ paymentOptions[0].desc }}</p>
                  </div>
                </div>
                <!-- 货到付款 -->
                <div
                  class="flex items-center p-4 rounded-lg cursor-pointer transition-colors"
                  :class="selectedPaymentIndex === 1 ? 'border-2 border-primary' : 'border border-gray-200 hover:border-primary/50'"
                  @click="selectPayment(1)"
                >
                  <div :class="selectedPaymentIndex === 1 ? 'mr-4 text-primary' : 'mr-4 text-gray-400'">
                    <span class="fa fa-money text-xl"></span>
                  </div>
                  <div>
                    <p class="font-medium">{{ paymentOptions[1].name }}</p>
                    <p class="text-gray-500 text-xs">{{ paymentOptions[1].desc }}</p>
                  </div>
                </div>
                <!-- 余额支付 -->
                <div
                  class="flex items-center p-4 rounded-lg cursor-pointer transition-colors"
                  :class="selectedPaymentIndex === 2 ? 'border-2 border-primary' : 'border border-gray-200 hover:border-primary/50'"
                  @click="selectPayment(2)"
                >
                  <div :class="selectedPaymentIndex === 2 ? 'mr-4 text-primary' : 'mr-4 text-gray-400'">
                    <span class="fa fa-gift text-xl"></span>
                  </div>
                  <div>
                    <p class="font-medium">{{ paymentOptions[2].name }}</p>
                    <p class="text-gray-500 text-xs">{{ paymentOptions[2].desc }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>


            <!-- 订单备注 -->
            <div class="bg-white rounded-xl shadow-sm overflow-hidden">
              <div class="p-6 border-b border-gray-100">
                <h3 class="font-bold text-lg text-gray-800">订单备注</h3>
              </div>

              <div class="p-6">
                <textarea
                  v-model="orderNote"
                  placeholder="请输入您的特殊要求，例如：请放在快递柜、工作日送货等..."
                  class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all resize-none h-24"
                ></textarea>
                <p class="text-gray-500 text-xs mt-2">请在200字以内填写您的特殊要求</p>
              </div>
            </div>

<!-- 商品清单 -->
<div class="bg-white rounded-xl shadow-sm overflow-hidden">
  <div class="p-6 border-b border-gray-100">
    <h3 class="font-bold text-lg text-gray-800">商品清单</h3>
  </div>

  <div class="divide-y divide-gray-100">
    <!-- 商品列表 -->
    <div v-for="(item, index) in cartItems" :key="item.id || index" class="p-6 hover:bg-gray-50 transition-colors">
      <div class="flex items-center gap-4">
        <img
          :src="item.image_urls && item.image_urls.length > 0
            ? (item.image_urls[0].startsWith('http') ? item.image_urls[0] : `http://127.0.0.1:8000/static/${item.image_urls[0]}`)
            : ''"
          :alt="item.name"
          class="w-20 h-20 object-cover rounded"
        >
        <div class="flex-1">
          <h4 class="font-medium">{{ item.name }}</h4>
          <p class="text-sm text-gray-500 mt-1">{{ item.spec }}</p>
          <p class="text-sm text-gray-500">数量: {{ item.quantity }}</p>
        </div>
        <div class="text-right">
          <p class="font-medium">¥{{ item.price.toFixed(2) }}</p>
        </div>
      </div>
    </div>
  </div>
</div>

          </div>

          <!-- 订单确认 -->
          <div class="lg:col-span-1">
            <div class="bg-white rounded-xl shadow-sm overflow-hidden sticky top-24">
              <div class="p-6 border-b border-gray-100">
                <h3 class="font-bold text-lg text-gray-800">订单确认</h3>
              </div>

              <div class="p-6">
                <div class="space-y-3 mb-6">
                  <div class="flex justify-between">
                    <span class="text-gray-600">商品总价</span>
                    <span>¥{{ calculateTotalPrice().toFixed(2) }}</span>
                  </div>
                  <div class="flex justify-between">
                    <span class="text-gray-600">运费</span>
                    <span>¥{{ selectedDelivery.price.toFixed(2) }}</span>
                  </div>
                  <div class="pt-3 border-t border-gray-100 flex justify-between font-bold text-lg">
                    <span>实付款</span>
                    <span class="text-primary">¥{{ calculateFinalPrice().toFixed(2) }}</span>
                  </div>
                </div>


                <button  class="w-full bg-primary hover:bg-dark text-white py-3 rounded-lg transition-colors font-medium mb-3 flex items-center justify-center" @click="submitOrder">
                  <span>提交订单</span>
                  <span class="fa fa-arrow-right ml-2"></span>
                </button>

                <p class="text-xs text-gray-500 mt-4 text-center">
                  <span class="fa fa-lock mr-1"></span> 提交订单即表示您同意我们的<a href="#" class="text-primary">服务条款</a>和<a href="#" class="text-primary">隐私政策</a>
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 底部信息栏 -->
    <Footer/>
    <!-- 返回顶部按钮 -->
    <button
      id="back-to-top"
      class="fixed bottom-6 right-6 bg-primary hover:bg-dark text-white w-12 h-12 rounded-full flex items-center justify-center shadow-lg transition-all opacity-0 invisible"
      @click="toTop"
    >
      <span class="fa fa-arrow-up"></span>
    </button>
  </div>
</template>

<script>
import Vue from 'vue'
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import BackTop from '@/components/BackTop.vue'
import api from '@/api/request'


// 引入消息提示插件（模拟Element UI的Message）
const Message = {
  success: (msg) => {
    alert(`成功: ${msg}`)
  },
  warning: (msg) => {
    alert(`警告: ${msg}`)
  },
  error: (msg) => {
    alert(`错误: ${msg}`)
  }
}
Vue.prototype.$message = Message

export default {
  name: 'Order',
  data() {
    return {
      showMobileMenu: false, // 移动端菜单显示状态
      showTop: false, // 返回顶部按钮显示状态
      orderNote: '', // 订单备注
      couponCode: '', // 优惠券码
      pointDeduction: 0, // 积分抵扣数量
      availablePoints: 2560, // 可用积分
      discount: 10, // 优惠金额
      selectedAddressIndex: 0, // 选中的地址索引
      selectedDeliveryIndex: 0, // 选中的配送方式索引
      selectedPaymentIndex: 0, // 选中的支付方式索引

      // 地址数据（初始为空，将从接口获取）
      addresses: [],

      // 配送方式
      deliveryOptions: [
        {
          name: '普通快递',
          desc: '预计3-5个工作日送达 | 满99元免运费',
          price: 0
        },
        {
          name: '加急快递',
          desc: '预计1-2个工作日送达',
          price: 20
        }
      ],

      // 支付方式
      paymentOptions: [
        {
          name: '微信支付',
          desc: '微信支付'
        },
        {
          name: '货到付款',
          desc: '支持现金、POS机刷卡'
        },
        {
          name: '余额支付',
          desc: '当前可用: ¥256.00'
        }
      ],

      // 购物车商品数据
      cartItems: [] // 用于接收购物车商品数据
    }
  },
  computed: {

    // 选中的配送方式
    selectedDelivery() {
      return this.deliveryOptions[this.selectedDeliveryIndex]
    },
    userProfile(){
      return this.$store.state.profile
    },

    // 选中的支付方式
    selectedPayment() {
      return this.paymentOptions[this.selectedPaymentIndex]
    },

    // 选中的地址
    selectedAddress() {
      return this.addresses[this.selectedAddressIndex] || {}
    }
  },
  mounted() {
    // 监听滚动事件
    window.addEventListener('scroll', this.handleScroll)
    // 初始化样式
    this.initStyles()
    // 加载用户地址数据
    this.loadUserAddresses()
     // 接收从购物车页面传递过来的商品数据
  if (this.$route.query.cartItems) {
    try {
      const cartItems = JSON.parse(this.$route.query.cartItems)
      // 转换数据格式以匹配订单页面需要的结构
      this.cartItems = cartItems.map(item => ({
        id: item.product_id,
        name: item.name,
        price: item.price,
        quantity: item.qty, // 购物车中是qty，订单中需要quantity
        image_urls: [item.img], // 转换为图片URL数组格式
        spec: item.spec || '无规格' // 处理规格信息
      }))
    } catch (error) {
      console.error('解析购物车数据失败:', error)
      this.$message.error('获取购物车数据失败')
    }
  } else {

    // 可以选择跳回购物车页面
    // this.$router.push('/cart')
  }

  // 新增：接收从AddAddress页面传递的新地址
  if (this.$route.query.newAddress) {
    try {
      const newAddress = JSON.parse(this.$route.query.newAddress);
      // 将新地址添加到地址列表
      this.addresses = [newAddress, ...this.addresses];
      // 默认选中新添加的地址
      this.selectedAddressIndex = 0;
    } catch (error) {
      console.error('解析新地址失败:', error);
    }
  }
  },
  beforeDestroy() {
    // 移除滚动事件监听
    window.removeEventListener('scroll', this.handleScroll)
    // 移除动态添加的样式
    this.removeStyles()
  },

  methods: {
    quaddaddress(){
      this.$router.push('/addaddress')
    },

    // 动态添加样式
    initStyles() {
      // 检查是否已添加样式
      if (document.getElementById('order-vue-styles')) return

      // 创建Tailwind基础样式
      const tailwindStyle = document.createElement('style')
      tailwindStyle.id = 'order-vue-styles'
      tailwindStyle.textContent = `
        /* Tailwind基础样式 */
        *, ::before, ::after {
          box-sizing: border-box;
          border-width: 0;
          border-style: solid;
          border-color: #e5e7eb;
        }
        ::before, ::after {
          --tw-content: '';
        }
        html {
          line-height: 1.5;
          -webkit-text-size-adjust: 100%;
          -moz-tab-size: 4;
          tab-size: 4;
          font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
          font-feature-settings: normal;
          font-variation-settings: normal;
        }
        body {
          margin: 0;
          line-height: inherit;
        }
        hr {
          height: 0;
          color: inherit;
          border-top-width: 1px;
        }
        abbr:where([title]) {
          -webkit-text-decoration: underline dotted;
          text-decoration: underline dotted;
        }
        h1, h2, h3, h4, h5, h6 {
          font-size: inherit;
          font-weight: inherit;
        }
        a {
          color: inherit;
          text-decoration: inherit;
        }
        b, strong {
          font-weight: bolder;
        }
        code, kbd, samp, pre {
          font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
          font-size: 1em;
        }
        small {
          font-size: 80%;
        }
        sub, sup {
          font-size: 75%;
          line-height: 0;
          position: relative;
          vertical-align: baseline;
        }
        sub {
          bottom: -.25em;
        }
        sup {
          top: -.5em;
        }
        table {
          text-indent: 0;
          border-color: inherit;
          border-collapse: collapse;
        }
        button, input, optgroup, select, textarea {
          font-family: inherit;
          font-feature-settings: inherit;
          font-variation-settings: inherit;
          font-size: 100%;
          font-weight: inherit;
          line-height: inherit;
          color: inherit;
          margin: 0;
          padding: 0;
        }
        button, select {
          text-transform: none;
        }
        button, [type='button'], [type='reset'], [type='submit'] {
          -webkit-appearance: button;
          background-color: transparent;
          background-image: none;
        }
        :-moz-focusring {
          outline: auto;
        }
        :-moz-ui-invalid {
          box-shadow: none;
        }
        progress {
          vertical-align: baseline;
        }
        ::-webkit-inner-spin-button, ::-webkit-outer-spin-button {
          height: auto;
        }
        [type='search'] {
          -webkit-appearance: textfield;
          outline-offset: -2px;
        }
        ::-webkit-search-decoration {
          -webkit-appearance: none;
        }
        ::-webkit-file-upload-button {
          -webkit-appearance: button;
          font: inherit;
        }
        summary {
          display: list-item;
        }
        blockquote, dl, dd, h1, h2, h3, h4, h5, h6, hr, figure, p, pre {
          margin: 0;
        }
        fieldset {
          margin: 0;
          padding: 0;
        }
        legend {
          padding: 0;
        }
        menu, ol, ul {
          list-style: none;
          margin: 0;
          padding: 0;
        }
        dialog {
          padding: 0;
        }
        textarea {
          resize: vertical;
        }
        input::placeholder, textarea::placeholder {
          opacity: 1;
          color: #9ca3af;
        }
        button, [role="button"] {
          cursor: pointer;
        }
        :disabled {
          cursor: default;
        }
        audio, canvas, embed, iframe, img, object, svg, video {
          display: block;
          vertical-align: middle;
        }
        img, video {
          max-width: 100%;
          height: auto;
        }
        [hidden] {
          display: none;
        }

        /* Tailwind工具类 */
        .container {
          width: 100%;
          margin-right: auto;
          margin-left: auto;
          padding-right: 1rem;
          padding-left: 1rem;
        }
        @media (min-width: 640px) {
          .container {
            max-width: 640px;
          }
        }
        @media (min-width: 768px) {
          .container {
            max-width: 768px;
          }
        }
        @media (min-width: 1024px) {
          .container {
            max-width: 1024px;
          }
        }
        @media (min-width: 1280px) {
          .container {
            max-width: 1280px;
          }
        }
        @media (min-width: 1536px) {
          .container {
            max-width: 1536px;
          }
        }
        .flex {
          display: flex;
        }
        .grid {
          display: grid;
        }
        .hidden {
          display: none;
        }
        .block {
          display: block;
        }
        .inline-block {
          display: inline-block;
        }
        .items-center {
          align-items: center;
        }
        .justify-between {
          justify-content: space-between;
        }
        .justify-center {
          justify-content: center;
        }
        .flex-col {
          flex-direction: column;
        }
        .flex-1 {
          flex: 1 1 0%;
        }
        .flex-wrap {
          flex-wrap: wrap;
        }
        .gap-2 {
          gap: 0.5rem;
        }
        .gap-4 {
          gap: 1rem;
        }
        .gap-6 {
          gap: 1.5rem;
        }
        .gap-8 {
          gap: 2rem;
        }
        .space-x-1 > :not([hidden]) ~ :not([hidden]) {
          --tw-space-x-reverse: 0;
          margin-right: calc(0.25rem * var(--tw-space-x-reverse));
          margin-left: calc(0.25rem * calc(1 - var(--tw-space-x-reverse)));
        }
        .space-x-4 > :not([hidden]) ~ :not([hidden]) {
          --tw-space-x-reverse: 0;
          margin-right: calc(1rem * var(--tw-space-x-reverse));
          margin-left: calc(1rem * calc(1 - var(--tw-space-x-reverse)));
        }
        .space-y-2 > :not([hidden]) ~ :not([hidden]) {
          --tw-space-y-reverse: 0;
          margin-top: calc(0.5rem * calc(1 - var(--tw-space-y-reverse)));
          margin-bottom: calc(0.5rem * var(--tw-space-y-reverse));
        }
        .space-y-3 > :not([hidden]) ~ :not([hidden]) {
          --tw-space-y-reverse: 0;
          margin-top: calc(0.75rem * calc(1 - var(--tw-space-y-reverse)));
          margin-bottom: calc(0.75rem * var(--tw-space-y-reverse));
        }
        .space-y-4 > :not([hidden]) ~ :not([hidden]) {
          --tw-space-y-reverse: 0;
          margin-top: calc(1rem * calc(1 - var(--tw-space-y-reverse)));
          margin-bottom: calc(1rem * var(--tw-space-y-reverse));
        }
        .divide-y > :not([hidden]) ~ :not([hidden]) {
          --tw-divide-y-reverse: 0;
          border-top-width: calc(1px * calc(1 - var(--tw-divide-y-reverse)));
          border-bottom-width: calc(1px * var(--tw-divide-y-reverse));
        }
        .rounded {
          border-radius: 0.25rem;
        }
        .rounded-lg {
          border-radius: 0.5rem;
        }
        .rounded-xl {
          border-radius: 0.75rem;
        }
        .rounded-full {
          border-radius: 9999px;
        }
        .rounded-l-lg {
          border-top-left-radius: 0.5rem;
          border-bottom-left-radius: 0.5rem;
        }
        .rounded-r-lg {
          border-top-right-radius: 0.5rem;
          border-bottom-right-radius: 0.5rem;
        }
        .border {
          border-width: 1px;
        }
        .border-2 {
          border-width: 2px;
        }
        .border-y {
          border-top-width: 1px;
          border-bottom-width: 1px;
        }
        .border-b {
          border-bottom-width: 1px;
        }
        .border-t {
          border-top-width: 1px;
        }
        .border-dashed {
          border-style: dashed;
        }
        .border-gray-100 {
          border-color: #f3f4f6;
        }
        .border-gray-200 {
          border-color: #e5e7eb;
        }
        .border-gray-300 {
          border-color: #d1d5db;
        }
        .border-gray-700 {
          border-color: #374151;
        }
        .bg-white {
          background-color: #ffffff;
        }
        .bg-gray-50 {
          background-color: #f9fafb;
        }
        .bg-gray-100 {
          background-color: #f3f4f6;
        }
        .bg-gray-200 {
          background-color: #e5e7eb;
        }
        .bg-green-600 {
          background-color: #16a34a;
        }
        .bg-primary\/10 {
          background-color: rgba(139, 90, 43, 0.1);
        }
        .p-2 {
          padding: 0.5rem;
        }
        .p-3 {
          padding: 0.75rem;
        }
        .p-4 {
          padding: 1rem;
        }
        .p-6 {
          padding: 1.5rem;
        }
        .py-2 {
          padding-top: 0.5rem;
          padding-bottom: 0.5rem;
        }
        .py-3 {
          padding-top: 0.75rem;
          padding-bottom: 0.75rem;
        }
        .py-6 {
          padding-top: 1.5rem;
          padding-bottom: 1.5rem;
        }
        .py-10 {
          padding-top: 2.5rem;
          padding-bottom: 2.5rem;
        }
        .px-2 {
          padding-left: 0.5rem;
          padding-right: 0.5rem;
        }
        .px-3 {
          padding-left: 0.75rem;
          padding-right: 0.75rem;
        }
        .px-4 {
          padding-left: 1rem;
          padding-right: 1rem;
        }
        .pl-10 {
          padding-left: 2.5rem;
        }
        .pr-4 {
          padding-right: 1rem;
        }
        .pb-4 {
          padding-bottom: 1rem;
        }
        .pt-3 {
          padding-top: 0.75rem;
        }
        .pt-6 {
          padding-top: 1.5rem;
        }
        .m-0 {
          margin: 0;
        }
        .mb-2 {
          margin-bottom: 0.5rem;
        }
        .mb-3 {
          margin-bottom: 0.75rem;
        }
        .mb-4 {
          margin-bottom: 1rem;
        }
        .mb-6 {
          margin-bottom: 1.5rem;
        }
        .mb-8 {
          margin-bottom: 2rem;
        }
        .mt-1 {
          margin-top: 0.25rem;
        }
        .mt-2 {
          margin-top: 0.5rem;
        }
        .mt-3 {
          margin-top: 0.75rem;
        }
        .mt-4 {
          margin-top: 1rem;
        }
        .mt-8 {
          margin-top: 2rem;
        }
        .mt-10 {
          margin-top: 2.5rem;
        }
        .ml-1 {
          margin-left: 0.25rem;
        }
        .ml-2 {
          margin-left: 0.5rem;
        }
        .ml-4 {
          margin-left: 1rem;
        }
        .ml-auto {
          margin-left: auto;
        }
        .-top-1 {
          top: -0.25rem;
        }
        .-right-1 {
          right: -0.25rem;
        }
        .top-3 {
          top: 0.75rem;
        }
        .top-4 {
          top: 1rem;
        }
        .right-3 {
          right: 0.75rem;
        }
        .right-4 {
          right: 1rem;
        }
        .bottom-6 {
          bottom: 1.5rem;
        }
        .right-6 {
          right: 1.5rem;
        }
        .relative {
          position: relative;
        }
        .absolute {
          position: absolute;
        }
        .fixed {
          position: fixed;
        }
        .sticky {
          position: sticky;
        }
        .top-0 {
          top: 0;
        }
        .top-24 {
          top: 6rem;
        }
        .left-0 {
          left: 0;
        }
        .w-5 {
          width: 1.25rem;
        }
        .w-8 {
          width: 2rem;
        }
        .w-10 {
          width: 2.5rem;
        }
        .w-12 {
          width: 3rem;
        }
        .w-20 {
          width: 5rem;
        }
        .w-full {
          width: 100%;
        }
        .max-w-md {
          max-width: 28rem;
        }
        .h-5 {
          height: 1.25rem;
        }
        .h-8 {
          height: 2rem;
        }
        .h-10 {
          height: 2.5rem;
        }
        .h-12 {
          height: 3rem;
        }
        .h-16 {
          height: 4rem;
        }
        .h-20 {
          height: 5rem;
        }
        .h-24 {
          height: 6rem;
        }
        .h-1 {
          height: 0.25rem;
        }
        .text-center {
          text-align: center;
        }
        .text-right {
          text-align: right;
        }
        .text-xl {
          font-size: 1.25rem;
          line-height: 1.75rem;
        }
        .text-lg {
          font-size: 1.125rem;
          line-height: 1.75rem;
        }
        .text-base {
          font-size: 1rem;
          line-height: 1.5rem;
        }
        .text-sm {
          font-size: 0.875rem;
          line-height: 1.25rem;
        }
        .text-xs {
          font-size: 0.75rem;
          line-height: 1rem;
        }
        .font-bold {
          font-weight: 700;
        }
        .font-semibold {
          font-weight: 600;
        }
        .font-medium {
          font-weight: 500;
        }
        .font-inter {
          font-family: 'Inter', system-ui, sans-serif;
        }
        .text-white {
          color: #ffffff;
        }
        .text-gray-500 {
          color: #6b7280;
        }
        .text-gray-600 {
          color: #4b5563;
        }
        .text-gray-700 {
          color: #374151;
        }
        .text-gray-800 {
          color: #1f2937;
        }
        .text-primary {
          color: #8B5A2B;
        }
        .text-secondary {
          color: #D2B48C;
        }
        .text-accent {
          color: #CD853F;
        }
        .text-light {
          color: #F5F5DC;
        }
        .text-dark {
          color: #3E2723;
        }
        .text-green-600 {
          color: #16a34a;
        }
        .bg-primary {
          background-color: #8B5A2B;
        }
        .bg-secondary {
          background-color: #D2B48C;
        }
        .bg-accent {
          background-color: #CD853F;
        }
        .bg-light {
          background-color: #F5F5DC;
        }
        .bg-dark {
          background-color: #3E2723;
        }
        .object-cover {
          object-fit: cover;
        }
        .shadow-sm {
          box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
        }
        .shadow-md {
          box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }
        .shadow-lg {
          box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        }
        .z-50 {
          z-index: 50;
        }
        .opacity-0 {
          opacity: 0;
        }
        .invisible {
          visibility: hidden;
        }
        .overflow-hidden {
          overflow: hidden;
        }
        .overflow-x-auto {
          overflow-x: auto;
        }
        .resize-none {
          resize: none;
        }
        .transform {
          transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
        }
        .-translate-y-1\/2 {
          --tw-translate-y: -50%;
        }
        .transition-all {
          transition-property: all;
          transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
          transition-duration: 150ms;
        }
        .transition-colors {
          transition-property: color, background-color, border-color, text-decoration-color, fill, stroke;
          transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
          transition-duration: 150ms;
        }
        .transition-transform {
          transition-property: transform;
          transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
          transition-duration: 150ms;
        }
        .duration-300 {
          transition-duration: 300ms;
        }
        .hover\:bg-gray-100:hover {
          background-color: #f3f4f6;
        }
        .hover\:bg-dark:hover {
          background-color: #3E2723;
        }
        .hover\:text-primary:hover {
          color: #8B5A2B;
        }
        .hover\:text-white:hover {
          color: #ffffff;
        }
        .hover\:text-light:hover {
          color: #F5F5DC;
        }
        .hover\:border-primary:hover {
          border-color: #8B5A2B;
        }
        .hover\:border-primary\/50:hover {
          border-color: rgba(139, 90, 43, 0.5);
        }
        .hover\:scale-105:hover {
          --tw-scale-x: 1.05;
          --tw-scale-y: 1.05;
        }
        .focus\:outline-none:focus {
          outline: 2px solid transparent;
          outline-offset: 2px;
        }
        .focus\:ring-1:focus {
          --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
          --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);
          box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
        }
        .focus\:ring-2:focus {
          --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
          --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);
          box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
        }
        .focus\:ring-primary:focus {
          --tw-ring-color: #8B5A2B;
        }
        .focus\:border-primary:focus {
          border-color: #8B5A2B;
        }
        .focus\:border-transparent:focus {
          border-color: transparent;
        }

        /* 响应式样式 */
        @media (min-width: 640px) {
          .sm\:text-xs {
            font-size: 0.75rem;
            line-height: 1rem;
          }
        }
        @media (min-width: 768px) {
          .md\:grid-cols-2 {
            grid-template-columns: repeat(2, minmax(0, 1fr));
          }
          .md\:grid-cols-4 {
            grid-template-columns: repeat(4, minmax(0, 1fr));
          }
          .md\:flex {
            display: flex;
          }
          .md\:hidden {
            display: none;
          }
          .md\:h-20 {
            height: 5rem;
          }
          .md\:space-x-4 {
            --tw-space-x-reverse: 0;
            margin-right: calc(1rem * var(--tw-space-x-reverse));
            margin-left: calc(1rem * calc(1 - var(--tw-space-x-reverse)));
          }
          .md\:space-x-8 {
            --tw-space-x-reverse: 0;
            margin-right: calc(2rem * var(--tw-space-x-reverse));
            margin-left: calc(2rem * calc(1 - var(--tw-space-x-reverse)));
          }
      `
      document.head.appendChild(tailwindStyle)
    },
    // 移除动态样式
    removeStyles() {
      const styleElement = document.getElementById('order-vue-styles')
      if (styleElement) {
        document.head.removeChild(styleElement)
      }
    },
    // 处理滚动事件
    handleScroll() {
      // 这里保留原滚动相关逻辑（如果有）
      this.showTop = window.scrollY > 300
      const backToTopBtn = document.getElementById('back-to-top')
      if (backToTopBtn) {
        if (this.showTop) {
          backToTopBtn.classList.remove('opacity-0', 'invisible')
          backToTopBtn.classList.add('opacity-100', 'visible')
        } else {
          backToTopBtn.classList.remove('opacity-100', 'visible')
          backToTopBtn.classList.add('opacity-0', 'invisible')
        }
      }
    },
    // 返回顶部
    toTop() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    },
async loadUserAddresses() {
  try {
    const userId = this.userProfile?.id;
    if (!userId) {
      this.$message.warning('请先登录后再查看地址');
      this.$router.push('/login');
      return;
    }

    // 发起请求
    const response = await api.get(`http://127.0.0.1:8000/userAddress/${userId}`);

    // 关键修复：匹配实际接口格式（code和data是同级）
    if (response.code === 200 && Array.isArray(response.data)) {
      this.addresses = response.data;

      // 修复默认地址判断（is_default字段名匹配）
      if (this.addresses.length > 0) {
        const defaultIndex = this.addresses.findIndex(addr => addr.is_default);
        this.selectedAddressIndex = defaultIndex !== -1 ? defaultIndex : 0;
      }
      console.log('地址加载成功:', this.addresses);
    } else {
      this.$message.warning('获取地址失败，返回格式异常');
      this.addresses = [];
    }
  } catch (error) {
    console.error('地址加载错误详情:', error);
    this.$message.error(`网络异常：${error.message || '获取地址失败'}`);
    this.addresses = [];
  }},

    // 选择地址
    selectAddress(index) {
  // 验证索引有效性
  if (index >= 0 && index < this.addresses.length) {
    this.selectedAddressIndex = index;
    const address = this.addresses[index];
    this.$message.success(`已选择地址: ${address.recipient_name || address.recipient} ${this.formatPhone(address.phone)}`);
  }
},
    // 格式化手机号（中间四位打码）
    formatPhone(phone) {
      if (!phone || phone.length !== 11) return phone
      return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
    },
    // 选择配送方式
    selectDelivery(index) {
      this.selectedDeliveryIndex = index
    },
    // 选择支付方式
    selectPayment(index) {
      this.selectedPaymentIndex = index
    },
    // 计算商品总价
    calculateTotalPrice() {
      return this.cartItems.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    },
    // 计算最终价格
    calculateFinalPrice() {
      const totalPrice = this.calculateTotalPrice()
      const deliveryPrice = this.selectedDelivery.price
      // 这里可添加优惠券、积分抵扣等逻辑
      return totalPrice + deliveryPrice
    },
    // 提交订单
   async submitOrder() {
  // 1. 基础验证（保持不变）
  if (!this.addresses.length || !this.selectedAddress.id) {
    this.$message.warning('请先选择收货地址')
    return
  }
  if (!this.cartItems.length) {
    this.$message.warning('购物车为空，无法提交订单')
    return
  }

  // 2. 构造订单数据（补充 order_number）
  const orderData = {
    user_id: this.userProfile.id,
    address_id: this.selectedAddress.id,
    order_number: "", // 关键：补充后端必填的 order_number 字段
    total_amount: this.calculateFinalPrice(),
    status: "待支付",
    payment_method: this.selectedPayment.name,
    payment_status: "待支付",
    remark: this.orderNote,
    refund_status: "无退款",
    items: this.cartItems.map(item => ({
      product_id: item.id,
      product_name: item.name,
      product_type: "coffee",
      product_image: item.image_urls?.[0] || '',
      quantity: item.quantity,
      price: item.price,
      total_price: item.price * item.quantity
    }))
  };

  try {
    console.log('订单数据:', orderData);
    // 3. 仅用 await 发送请求，不混合 .then/.catch
    const response = await api.post('http://127.0.0.1:8000/order/', orderData);

    // 4. 成功逻辑（此时 response 能正确拿到后端返回）
    // 现在能正常执行
    if (response.code === 200) { // 注意：后端返回的 code 在 response.data 里

      // 跳转支付页时，携带后端返回的真实订单号（response.data.data.order_number）
this.$router.push({
        path: '/pay',
        query: { orderNumber: response.data.order_number }
      });
    } else {
      this.$message.error(`提交失败: ${response.code}`);
    }

  } catch (error) {
    // 5. 错误处理（打印完整错误，方便定位）
    console.error('后端错误详情:', error.response?.data);
    // 解析后端返回的 detail 错误（数组格式）
    const errorMsg = error.response?.data?.detail
      ? error.response.data.detail.map(item => `${item.loc.join('.')}: ${item.msg}`).join('; ')
      : '未知错误';
    this.$message.error(`参数错误: ${errorMsg}`);
  }
}

  }
}
</script>

<style scoped>
/* 局部样式补充，确保样式隔离 */
.order-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 导航栏样式补充 */
header {
  transition: all 0.3s ease;
}

/* 商品图片样式 */
img {
  transition: transform 0.3s ease;
}
img:hover {
  transform: scale(1.05);
}

/* 按钮交互效果 */
button {
  transition: all 0.2s ease;
}
button:active {
  transform: scale(0.98);
}

/* 表单元素样式 */
input:focus, textarea:focus {
  transition: all 0.2s ease;
}

/* 地址卡片样式 */
div[class*="border-primary"] {
  position: relative;
  z-index: 1;
}

/* 订单步骤指示器样式 */
div[class*="w-1/3"] {
  position: relative;
}

/* 底部样式 */
footer {
  margin-top: auto;
}

/* 修复响应式布局问题 */
@media (max-width: 1024px) {
  .lg\:col-span-2, .lg\:col-span-1 {
    grid-column: span 1 !important;
  }
}

@media (max-width: 768px) {
  .md\:grid-cols-4 {
    grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
  }
  .md\:h-20 {
    height: 4rem !important;
  }
  .md\:space-x-8 {
    gap: 1rem !important;
  }
}

@media (max-width: 640px) {
  .md\:hidden {
    display: none !important;
  }
  .md\:flex {
    display: flex !important;
  }
  .text-2xl {
    font-size: 1.5rem !important;
  }
  .py-10 {
    padding-top: 2rem !important;
    padding-bottom: 2rem !important;
  }
}
</style>
